using UnityEngine;
using System.Collections;

[RequireComponent(typeof(TP_Controller))]
[RequireComponent(typeof(TP_Motor))]

public class ThirdPersonPushBodies : MonoBehaviour
{
	public float pushPower = 0.5f;
	public LayerMask pushLayers = -1;
	
	private TP_Controller controller;
	private TP_Motor motor;
	
	void Start()
	{
		controller = GetComponent<TP_Controller>();
		motor = GetComponent<TP_Motor>();
	}
	
	void OnControlllerHit(ControllerColliderHit hit)
	{
		Rigidbody body = hit.collider.attachedRigidbody;
		
		//If no rigidbody
		if(body == null || body.isKinematic)
		{
			return;
		}
		
		//Ignore pushing through those rigidbodies
		LayerMask bodyLayerMask = 1 << body.gameObject.layer;
		if((bodyLayerMask & pushLayers.value) == 0)
		{	
		return;	
		}	
		
		//Calculate push direction from move direction, only push objects to the sides
		//Never up and down
		Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
		
		//Push with more speed, but never more than walkspeed
		body.velocity = pushDir * pushPower * Mathf.Min(motor.ForwardSpeed, motor.BackwardSpeed);
		
	}
}